package com.example.service.Imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.pojo.Musicinfo;
import com.example.common.pojo.collection;
import com.example.common.pojo.musicarticle;
import com.example.common.pojo.musicuser;
import com.example.dao.MusicArticleMapper;
import com.example.dao.MusicCollectMapper;
import com.example.dao.MusicInfoMapper;
import com.example.service.Musicinfoservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class MusicinfoserviceImp extends ServiceImpl<MusicInfoMapper, Musicinfo> implements Musicinfoservice {

    /*
     * 先判断redis里面是否有setKey的set集合，
     * 1.如果没有就：
     *   在redis里面存储一个key为setKey的set集合，里面存储userId
     *   在再redis里面存储一个key为"setKeyid"+String.valueOf(userId)的集合，里面存储articleId
     * 2.如果有，就直接取值
     *   setOps.members("setKeyid"+String.valueOf(userId));取出指定的set集合的值
     *   这内容就是用户收藏的歌曲id的值
     *
     * 在分页展示数据是调出用户收藏的歌曲id的值，遍历setlike为true为收藏的歌
     *
     * 点击收藏为往set里面存值，取消收藏为删除set里面的值
     *
     * 在redis里面存储一个key为userId的set集合,里面存储articleId 这内容就是用户收藏的歌曲id的值
     *
     * 做一个定时，向数据库更新数据
     *
     * */

    @Autowired
    private MusicInfoMapper musicInfoMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MusicCollectMapper musicCollectMapper;

    @Autowired
    private MusicArticleMapper musicArticleMapper;

/*
*   用户收藏的列表
* */
    @Override
    public List<musicarticle> collectservice(String token) {
        String userinfo = stringRedisTemplate.opsForValue().get(token);
        musicuser musicuserinfo = JSON.parseObject(userinfo,musicuser.class);
        ArrayList<String> articleidlist = new ArrayList<>();
        LambdaQueryWrapper<collection> wapper = new LambdaQueryWrapper<>();
        wapper.eq(collection::getUserId,String.valueOf(musicuserinfo.getId()));
        List<collection> collectionlist = musicCollectMapper.selectList(wapper);
        for (collection c: collectionlist
             ) {
            articleidlist.add(String.valueOf(c.getArticleId()));
        }
        Set<String> set1 = stringRedisTemplate.boundSetOps(String.valueOf(musicuserinfo.getId())).members();
        for (String element : set1) {
            articleidlist.add(element);
        }
        List<musicarticle> musicarticless = musicArticleMapper.selectBatchIds(articleidlist);
        return musicarticless;
    }

    //    点击收藏成功
//    将用户id存在setKey的set集合中，值为用户id,无序不可重复
//    再将用户id在存一个set集合,内部是文章id
    @Override
    public boolean storeUserTrends(Long articleId, Long userId) {
        BoundSetOperations setKey = stringRedisTemplate.boundSetOps("setKey");
        Long add =setKey.add(String.valueOf(userId));
//      返回的add的值，如果key值的set集合里面已经存在这个值，则返回0，如果不存在则添加返回1
        BoundSetOperations setKeyid = stringRedisTemplate.boundSetOps(String.valueOf(userId));
        Long add1 = setKeyid.add(String.valueOf(articleId));
//        点赞数，是否点赞进行加减
        Double isnewScore = stringRedisTemplate.opsForZSet().incrementScore("isperfect", String.valueOf(articleId), 1);
        Double newScore = stringRedisTemplate.opsForZSet().incrementScore("perfect", String.valueOf(articleId), 1);
        if (add1.intValue() !=0){
            return true;
        }else {
            return false;
        }
    }

//    取消收藏
    @Override
    public boolean unstoreUserTrends(Long articleId, Long userId) {
//      返回值为0，则不存在，为1则存在
        Long result1 = stringRedisTemplate.boundSetOps(String.valueOf(userId)).remove(String.valueOf(articleId));
//        点赞数，是否点赞进行加减
        Double isnewScore = stringRedisTemplate.opsForZSet().incrementScore("isperfect", String.valueOf(articleId), -1);
        Double newScore = stringRedisTemplate.opsForZSet().incrementScore("perfect", String.valueOf(articleId), -1);
        LambdaQueryWrapper<collection> wapper = new LambdaQueryWrapper<>();
        if (result1.intValue() != 0){
            return true;
        }else {
            wapper.eq(collection::getUserId,userId);
            wapper.eq(collection::getArticleId,articleId);
            int one = musicCollectMapper.delete(wapper);
            if (one == 1){
                return true;
            }else {
                return false;
            }
        }

    }

    /*
    * 返回值，是否收藏，收藏iscollection字段为true,反之
    * */
    @Override
    public List<Musicinfo> forlist(String token, List<Musicinfo> infolist) {
        String userinfo = stringRedisTemplate.opsForValue().get(token);
        musicuser musicuserinfo = JSON.parseObject(userinfo,musicuser.class);
        for (Musicinfo m:infolist
        ) {
//            空指针异常，可能时无法获取用户信息，用户的id，token失效
            if (stringRedisTemplate.boundSetOps(String.valueOf(musicuserinfo.getId())).isMember(String.valueOf(m.getId()))){
                m.setIscollection(1);
            }
            continue;
        }
        return infolist;
    }

}
